package com.yxw.yxnet_cd_center.customer_service.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.customer_service.vo.UserTokenVo;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
public class JwtUtil {

    /**
     * 生成token，自定义过期时间 毫秒
     * @param yxUserTokenVo 参数封装
     * @return String
     */
    public static String generateToken(UserTokenVo yxUserTokenVo, Long checkCode) {
        try {
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(CommonConstant.JWT_TOKEN);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");

            return JWT.create()
                    .withHeader(header)
                    .withClaim("checkCode", checkCode)
                    .withClaim("userId", yxUserTokenVo.getUserId())
                    .withClaim("token", JSONObject.toJSONString(yxUserTokenVo))
                    .withClaim("expireTime",new Date(new Date().getTime() + 30*60*1000))
                    .sign(algorithm);
        } catch (Exception e) {
            log.error("generate token occur error, error is:{}", e);
            return null;
        }
    }

    /**
     * 检验token是否正确
     * @param token token
     * @return YxSysUserTokenVo
     */
    public static UserTokenVo parseToken(String token) {
        Algorithm algorithm = Algorithm.HMAC256(CommonConstant.JWT_TOKEN);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT jwt = verifier.verify(token);
        String yxSysUserTokenVo = jwt.getClaim("token").asString();
        return JSON.parseObject(yxSysUserTokenVo, UserTokenVo.class);
    }
}
